package com.ml.service.impl;

import com.ml.dao.BaseDao;
import com.ml.dao.DkAccessDao;
import com.ml.model.KqData;
import com.ml.model.KqDataException;
import com.ml.model.MLUser;
import com.ml.service.KqAccessService;
import com.ml.service.KqDataExceptionService;
import com.ml.service.KqDataService;
import com.ml.service.MLUserService;
import com.ml.util.UtilDate;
import com.ml.util.UtilProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**上海读取 Access 数据库的 serviceImpl */
@Service
public class KqAccessServiceImpl implements KqAccessService {



    @Autowired
    private MLUserService mLUserService;

    @Autowired
    private KqDataService kqDataService;

    @Autowired
    private DkAccessDao dkAccessDao;

    @Autowired
    private BaseDao<KqData> basedao;

    @Autowired
    private KqDataExceptionService kqDataExceptionService;

    public final  String loactionidsh = UtilProperties.getConfig("locationid.sh");
    public final  String loactionidtj = UtilProperties.getConfig("locationid.tj");
    public final  String loactioniddl = UtilProperties.getConfig("locationid.dl");



    public int writeMysqlDkInfo(String locationid,String date){
        int num = 0;//影响行数
        if(!StringUtils.hasText(date)){//没传递时间默认为 今天的
            Calendar ca = Calendar.getInstance();
            date = ca.get(Calendar.YEAR) + "/" + ( ca.get(Calendar.MONTH)+1 ) + "/" + ca.get(Calendar.DATE);
        }
        String date1 = "";//构造 2019/5/9 为 2019-05-09
        int y = Integer.valueOf(date.split("/")[0]);
        int m = Integer.valueOf(date.split("/")[1]);
        int d = Integer.valueOf(date.split("/")[2]);
        date1 = y + "-" + ( m>9?m:"0"+m ) + "-" +( d>9?d:"0"+d );


        //首先获取 上海 在职 人员信息

        //读取上海分部的所有人
        List<MLUser> userList = new ArrayList<>();
        List<KqData> listBaseData = new ArrayList();//从考勤机 读取该天的数据
        //从 ml_hrmschedulesign 读取该分部 当天已经插入的数据
        List<KqData> listExitsData =kqDataService.getListByDate(date1,Integer.valueOf(locationid));
        List<KqDataException> kqDataExceptions = kqDataExceptionService.getByLocationid(locationid);
        if(locationid.equals(loactionidsh)){//上海
            userList = mLUserService.getListByLocation1(Integer.valueOf(loactionidsh));
            listBaseData = dkAccessDao.getDkRecordSh(date);
        }else if(locationid.equals(loactioniddl)){//大连
            userList = mLUserService.getListByLocation1(Integer.valueOf(loactioniddl));
            listBaseData = dkAccessDao.getDkRecordDl(date);
        }else if(locationid.equals(loactionidtj)){//天津
            userList = mLUserService.getListByLocation1(Integer.valueOf(loactionidtj));
            listBaseData = dkAccessDao.getDkRecordTj(date);
        }



        if(userList!=null && userList.size()>0){//下面的循环是核心东西，要执行很长时间，没办法优化
            //和泛微的人员数据库进行匹配
            //最终要同步的数据
            List<KqData> listTbData = new ArrayList();//最终 OA系统 ml_hrmschedulesign 没有写入的考勤数据
            for(MLUser user : userList ){
                String userName1 = user.getLastname();//从泛微数据库里获取 人员姓名
                for(KqData kq : listBaseData){//循环 从access数据库读取的数据
                    String userName2 = kq.getUserName();
                    if(StringUtils.hasText(userName2)){
                        if(userName1.equals(userName2)){//考勤和泛微的 用户名要一致
                            KqData kqData = kq;
                            int userId = user.getId();//获取用户ID，这个不可能为空的
                            kqData.setUserId(userId);
                            String datestr = kqData.getSignDate().substring(0,10);
                            kqData.setSignDate(datestr);
                            kqData.setBelongdate(datestr);
                            kqData.setLocationid(Integer.valueOf(locationid));
                            if(isExitsKqData( listExitsData, userId,datestr,kqData.getSignTime(),userName1,kqDataExceptions,locationid)){
                                listTbData.add(kqData);
                            }
                        }
                    }
                }
            }
            //最后批量保存数据
            if(listTbData!=null && listTbData.size()>0){
                basedao.saveBatch(listTbData);
                num = listTbData.size();
            }

        }
        return num;
    }

    /**
     *  判断 要执行插入的access数据是否是 已经插入的数据
     * @return true 允许插入
     */
    public  boolean isExitsKqData(List<KqData> list, Integer userId0, String signDate0, String signTime0, String userName0, List<KqDataException> list2, String locationid){
        boolean flag = true;
        //获取当天已经插入到泛微数据库的所有的考勤数据
        //List<KqData> list = kqDataService.getListByDate(date);
        List<KqData> listDate = new ArrayList<>();//某人当天的考勤数据
        if(list!=null && list.size()>0){
            for(KqData kqData : list){
                int userId1 = kqData.getUserId();
                String signDate1 = kqData.getSignDate();
                String signTime1 = kqData.getSignTime();
                if(userId1==userId0 && signDate0.equals(signDate1) && signTime0.equals(signTime1)){
                    flag = false;
                    break;
                }
                if( userId1==userId0 && signDate0.equals(signDate1) ){
                    listDate.add(kqData);
                }
            }
        }



        KqData earlykq = new KqData();
        if(listDate!=null && listDate.size()>0){
            //判断是否是异常数据
            earlykq = listDate.get(0);
            //获取当天该人的最早的 打开时间
            int earlyTime = Integer.valueOf(earlykq.getSignTime().replaceAll(":",""));
            //本次打卡时间
            int thisTime = Integer.valueOf(signTime0.replaceAll(":",""));
            if(thisTime<earlyTime){//本次 获取的打卡时间，比系统第一次记录的打卡时间 小，说明是修改的数据
                flag = false;
                boolean flag2=true;
                String earlData = signDate0 + " "+earlykq.getSignTime();//最早打卡 时间
                String ycData = signDate0 + " "+signTime0;// 异常数据
                if(list2!=null && list2.size()>0){
                    for(KqDataException kex : list2){//判断是否插入过异常数据
                        //异常数据已经录入
                        if(kex.getUseid().equals(userId0+"") && kex.getEarlData().equals(earlData) && kex.getYcData().equals(ycData)  ){
                            flag2 = false;
                            break;
                        }
                    }
                }
                if(flag2){
                    KqDataException ke = new  KqDataException();
                    ke.setCreateTime(UtilDate.getNowTime());
                    ke.setEarlData(earlData);
                    ke.setUseid(userId0+"");
                    ke.setUseName(userName0);
                    ke.setYcData(ycData);
                    ke.setLocationid(locationid);
                    if(locationid.equals("1")){
                        ke.setLocation("上海皿鎏");
                    }else if(locationid.equals("2")){
                        ke.setLocation("大连皿鎏");
                    }else if(locationid.equals("3")){
                        ke.setLocation("天津皿鎏");
                    }
                    kqDataExceptionService.save(ke);
                }
            }
        }
        return flag;
    }




    //获取指定天数的考勤数据
    public int writeMysqlDkInfoSh(String date){
        return writeMysqlDkInfo( loactionidsh , date);
    }
    //获取上一天的时间
    public int writeMysqlDkInfoTodaySh(){
        return writeMysqlDkInfo( loactionidsh , "");
    }


    public int writeMysqlDkInfoTj(String date){
        return writeMysqlDkInfo( loactionidtj , date);
    }
    public int writeMysqlDkInfoTodayTj(){
        return writeMysqlDkInfo( loactionidtj , "");
    }


    public int writeMysqlDkInfoDl(String date){
        return writeMysqlDkInfo( loactioniddl , date);
    }
    public int writeMysqlDkInfoTodayDl(){
        return writeMysqlDkInfo( loactioniddl , "");
    }



}
